/**
 * OCR 快速测试脚本
 * 用于测试修复后的OCR功能
 */

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

class OCRQuickTest {
    constructor() {
        this.pluginDir = __dirname;
        this.pythonExe = path.join(this.pluginDir, 'python', 'python.exe');
        this.ocrScript = path.join(this.pluginDir, 'ocr_infer.py');
    }

    async log(message) {
        const timestamp = new Date().toISOString().substring(11, 19);
        console.log(`[${timestamp}] ${message}`);
    }

    async runCommand(command, args, options = {}) {
        return new Promise((resolve) => {
            const process = spawn(command, args, {
                stdio: ['pipe', 'pipe', 'pipe'],
                ...options
            });

            let stdout = '';
            let stderr = '';

            process.stdout.on('data', (data) => {
                const chunk = data.toString();
                stdout += chunk;
                // 实时显示进度
                if (chunk.includes('info')) {
                    try {
                        const lines = chunk.split('\n');
                        for (const line of lines) {
                            if (line.trim() && line.includes('info')) {
                                const parsed = JSON.parse(line.trim());
                                if (parsed.info) {
                                    console.log(`  📋 ${parsed.info}`);
                                }
                            }
                        }
                    } catch (e) {
                        // 忽略解析错误
                    }
                }
            });

            process.stderr.on('data', (data) => {
                stderr += data.toString();
            });

            process.on('close', (code) => {
                resolve({ code, stdout, stderr });
            });

            process.on('error', (error) => {
                resolve({ code: -1, error: error.message, stdout: '', stderr: '' });
            });
        });
    }

    async testWithRealImage(imagePath) {
        await this.log(`🖼️ 测试真实图片OCR: ${imagePath}`);
        
        if (!fs.existsSync(imagePath)) {
            await this.log(`❌ 图片文件不存在: ${imagePath}`);
            return false;
        }

        const startTime = Date.now();
        const result = await this.runCommand(this.pythonExe, [this.ocrScript, imagePath, 'ch'], {
            timeout: 180000 // 3分钟超时
        });
        const endTime = Date.now();
        const duration = (endTime - startTime) / 1000;

        await this.log(`⏱️ OCR执行耗时: ${duration.toFixed(1)}秒`);
        await this.log(`📊 执行结果: 退出代码=${result.code}, 输出长度=${result.stdout.length}, 错误长度=${result.stderr.length}`);

        if (result.stdout) {
            await this.log('📤 标准输出:');
            console.log(result.stdout);
        }

        if (result.stderr && result.stderr.length > 0) {
            await this.log('⚠️ 标准错误:');
            console.log(result.stderr.substring(0, 500) + (result.stderr.length > 500 ? '...' : ''));
        }

        // 分析结果
        if (result.code === 0) {
            try {
                const lines = result.stdout.split('\n').filter(line => line.trim());
                const finalLine = lines[lines.length - 1];
                const parsed = JSON.parse(finalLine);
                
                if (parsed.text && parsed.success) {
                    await this.log(`✅ OCR成功! 识别文本长度: ${parsed.text.length}`);
                    await this.log(`📝 识别内容预览: ${parsed.text.substring(0, 100)}${parsed.text.length > 100 ? '...' : ''}`);
                    return true;
                } else {
                    await this.log(`⚠️ OCR完成但结果异常: ${JSON.stringify(parsed)}`);
                    return false;
                }
            } catch (e) {
                await this.log(`❌ JSON解析失败: ${e.message}`);
                return false;
            }
        } else {
            await this.log(`❌ OCR失败，退出代码: ${result.code}`);
            return false;
        }
    }

    async findTestImage() {
        // 查找可能的测试图片
        const possiblePaths = [
            path.join(this.pluginDir, '..', '..', 'xxx.png'),
            path.join(process.cwd(), 'xxx.png'),
            'D:\\workspaceSelf\\xxx.png',
            path.join(this.pluginDir, 'test.png'),
            path.join(this.pluginDir, 'test.jpg')
        ];

        for (const testPath of possiblePaths) {
            if (fs.existsSync(testPath)) {
                return testPath;
            }
        }

        return null;
    }

    async runQuickTest() {
        await this.log('🚀 开始OCR快速测试...');
        
        // 检查基本环境
        if (!fs.existsSync(this.pythonExe)) {
            await this.log('❌ Python环境不存在，请先运行环境初始化');
            return;
        }

        if (!fs.existsSync(this.ocrScript)) {
            await this.log('❌ OCR脚本不存在，请检查插件完整性');
            return;
        }

        // 查找测试图片
        const testImage = await this.findTestImage();
        if (!testImage) {
            await this.log('⚠️ 未找到测试图片，请手动指定图片路径');
            await this.log('💡 使用方法: node test_quick.js "图片路径"');
            return;
        }

        await this.log(`📁 找到测试图片: ${testImage}`);
        
        // 执行测试
        const success = await this.testWithRealImage(testImage);
        
        if (success) {
            await this.log('🎉 测试完成: OCR功能正常工作!');
        } else {
            await this.log('⚠️ 测试完成: OCR存在问题，请检查日志');
        }

        // 提供建议
        await this.log('\n💡 建议:');
        await this.log('1. 如果首次运行，下载模型可能需要几分钟');
        await this.log('2. 确保网络连接正常（模型下载需要）');
        await this.log('3. 大图片会增加处理时间，建议压缩到2MB以下');
        await this.log('4. 如果持续失败，可以运行 node diagnostic.js 进行详细诊断');
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const tester = new OCRQuickTest();
    
    // 检查是否提供了图片路径参数
    const imagePath = process.argv[2];
    if (imagePath) {
        tester.testWithRealImage(imagePath).then(success => {
            process.exit(success ? 0 : 1);
        }).catch(console.error);
    } else {
        tester.runQuickTest().catch(console.error);
    }
}

module.exports = OCRQuickTest;